/**
 * @description 文件处理
*/

import ebus from './ebus.js'

let isPlus = false
// #ifdef APP-PLUS
isPlus = true
// #endif

const filer = {
  /**
   * @function 请求图片并转化为base64
  */
  fetchImageToBase64(url) {
    return this.fetch(url).then(res => {
      let base64 = this.arrayBufferToBase64(res.data)
      base64 = 'data:image/jpeg;base64,' + base64
      return base64
    })
  },

  /**
   * @function 文件转化为base64
  */
  arrayBufferToBase64 (data) {
    return uni.arrayBufferToBase64(data)
  },

  pathToBase64: pathToBase64,

  base64ToPath: base64ToPath,

  imagePathToFile (path) {
    const getLocalFilePath = this.getLocalFilePath
    return new Promise(function(resolve, reject) {
      if (typeof window === 'object' && 'document' in window) {
        var xhr = new XMLHttpRequest()
        xhr.open('GET', path, true)
        xhr.responseType = 'blob'
        xhr.onload = function() {
          if (this.status === 200) {
            try {
              let name = path.replace(/.+\//, '')
              let type = name.replace(/.+\./, '')
              let file = new File([this.response], name, { type: 'image/' + type })
              resolve(file)
            } catch (e) {
              reject(e)
            }
          }
        }
        xhr.onerror = reject
        xhr.send()
        return
      }
      if (typeof plus === 'object') {
        plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
          entry.file(function(file) {
            resolve(file)
          }, function(e) {
            reject(e)
          })
        }, function(e) {
          reject(e)
        })
        return
      }
      if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
        wx.getFileSystemManager().readFile({
            filePath: path,
            encoding: 'base64',
            success (res) {
              resolve('data:image/jpeg;base64,' + res.data)
            },
            fail (e) {
              reject(e)
            }
        })
        return
      }
      reject(new Error('not support'))
    })
  },

  /**
   * base64字符串转成文件
   * @param {String} base64Str // 允许包含前缀
   * @param {String} fileName // 文件名称：1663061363470.xlsx
   * @param {Object} callback // 返回本地路径径URL，file:///xxx/doc/1663062980631.xlsx
   */
  base64ToFile (base64Str, fileName, callback) {
    // 去除base64前缀
    var index = base64Str.indexOf(',')
    var base64Str = base64Str.slice(index + 1,base64Str.length)
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
      fs.root.getFile(fileName, { create: true }, function(entry) {
        // 获得本地路径URL，file:///xxx/doc/1663062980631.xlsx
        var fullPath = entry.fullPath
        let platform = uni.getSystemInfoSync().platform
        if (platform === 'android') {
          var Base64 = plus.android.importClass("android.util.Base64")
          var FileOutputStream = plus.android.importClass("java.io.FileOutputStream")
          try {
            var out = new FileOutputStream(fullPath)
            // 此处Base64.decode有长度限制，如果不能满足需求，可以考虑换成官方原生插件市场的【Base64转文件】
            var bytes = Base64.decode(base64Str, Base64.DEFAULT)
            out.write(bytes)
            out.close()
            // 回调
            callback && callback(entry.toLocalURL())
           } catch (e) {
            console.log(e.message)
          }
        } else if (platform == 'ios') {
          var NSData = plus.ios.importClass('NSData')
          var nsData = new NSData()
          nsData = nsData.initWithBase64EncodedStringoptions(base64Str,0)
          if (nsData) {
            nsData.plusCallMethod({writeToFile: fullPath, atomically: true})
            plus.ios.deleteObject(nsData)
          }
          // 回调
          callback && callback(entry.toLocalURL())
        }
      })
    })
  },

  /**
   * @function 请求文件
  */
  fetch (url) {
    return new Promise(function(resolve, reject){
      uni.request({
        url: url,
        method: 'GET',
        responseType: 'arraybuffer',
        success (res) {
          if (res.statusCode === 200) {
            resolve(res)
          } else {
            reject(res)
          }
        },
        fail (e) {
          reject(e)
        }
      })
    })
  },

  /**
   * @function 读取本地文件
  */
  readFile (filePath) {
    return new Promise(function(ressolve, reject){
      plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
        entry.file((file) => {
          const fileReader = new plus.io.FileReader()
          fileReader.onloadend = (evt) => {
            ressolve(evt)
          }
          fileReader.onerror = function (e) {
            reject(e)
          }
          fileReader.readAsText(file, 'utf-8')
        }, (e) => {
          reject(e)
        })
      }, (e) => {
        reject(e)
      })
    })
  },
  // 上传文件
  uploadFile ({url, params = {}, options = {}, vm} = {}) {
    return new Promise(function (resolve, reject) {
      let data = {
        url: url,
        name: params.name,
        formData: params.formData,
        header: {
          Authorization: vm.vuex_token
        },
        success: (res) => {
          let data = res.data
          try {
            let result = JSON.parse(data)
            data = result
          } catch (e) {
            data = res.data
          }
          resolve(data)
					// 401响应
					if (String(res.statusCode) === '401' || String(data?.code) === '401') {
						ebus.$emit('on401', { res, req: data, vm })
					}
        },
        fail (res) {
          reject(res)
					// 401响应
					if (String(res.statusCode) === '401' || String(res?.data?.code) === '401') {
						ebus.$emit('on401', { res, vm })
					}
        }
      }
      if (params.file) {
        data.file = params.file
      } else if (params.filePath) {
        data.filePath = params.filePath
      }
      uni.uploadFile(data)
    })
  },

  // 删除本地图片
  deleteImage (item) {
    item = item || {}
    if (!/doc/i.test(item.path) || !isPlus) {
      return Promise.resolve(true)
    }
    return new Promise((resolve, reject) => {
      plus.io.resolveLocalFileSystemURL(item.path, function(entry) {
        entry.remove(function(e) {
          resolve(e)
        }, function(e) {
          loger.error(e)
          reject(e)
        })
      })
    })
  }
}

export default filer

function getLocalFilePath(path) {
    if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
        return path
    }
    if (path.indexOf('file://') === 0) {
        return path
    }
    if (path.indexOf('/storage/emulated/0/') === 0) {
        return path
    }
    if (path.indexOf('/') === 0) {
        var localFilePath = plus.io.convertAbsoluteFileSystem(path)
        if (localFilePath !== path) {
            return localFilePath
        } else {
            path = path.substr(1)
        }
    }
    return '_www/' + path
}

function dataUrlToBase64(str) {
    var array = str.split(',')
    return array[array.length - 1]
}

var index = 0
function getNewFileId() {
    return Date.now() + String(index++)
}

function biggerThan(v1, v2) {
    var v1Array = v1.split('.')
    var v2Array = v2.split('.')
    var update = false
    for (var index = 0; index < v2Array.length; index++) {
        var diff = v1Array[index] - v2Array[index]
        if (diff !== 0) {
            update = diff > 0
            break
        }
    }
    return update
}

export function pathToBase64(path) {
    return new Promise(function(resolve, reject) {
        if (typeof window === 'object' && 'document' in window) {
            if (typeof FileReader === 'function') {
                var xhr = new XMLHttpRequest()
                xhr.open('GET', path, true)
                xhr.responseType = 'blob'
                xhr.onload = function() {
                    if (this.status === 200) {
                        let fileReader = new FileReader()
                        fileReader.onload = function(e) {
                            resolve(e.target.result)
                        }
                        fileReader.onerror = reject
                        fileReader.readAsDataURL(this.response)
                    }
                }
                xhr.onerror = reject
                xhr.send()
                return
            }
            var canvas = document.createElement('canvas')
            var c2x = canvas.getContext('2d')
            var img = new Image
            img.onload = function() {
                canvas.width = img.width
                canvas.height = img.height
                c2x.drawImage(img, 0, 0)
                resolve(canvas.toDataURL())
                canvas.height = canvas.width = 0
            }
            img.onerror = reject
            img.src = path
            return
        }
        if (typeof plus === 'object') {
            plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
                entry.file(function(file) {
                    var fileReader = new plus.io.FileReader()
                    fileReader.onload = function(data) {
                        resolve(data.target.result)
                    }
                    fileReader.onerror = function(error) {
                        reject(error)
                    }
                    fileReader.readAsDataURL(file)
                }, function(error) {
                    reject(error)
                })
            }, function(error) {
                reject(error)
            })
            return
        }
        if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
            wx.getFileSystemManager().readFile({
                filePath: path,
                encoding: 'base64',
                success: function(res) {
                    resolve('data:image/png;base64,' + res.data)
                },
                fail: function(error) {
                    reject(error)
                }
            })
            return
        }
        reject(new Error('not support'))
    })
}

export function base64ToPath(base64, fileName) {
  return new Promise(function(resolve, reject) {
    if (typeof window === 'object' && 'document' in window) {
      return resolve(base64)
      base64 = base64.split(',')
      var type = base64[0].match(/:(.*?);/)[1]
      var str = atob(base64[1])
      var n = str.length
      var array = new Uint8Array(n)
      while (n--) {
        array[n] = str.charCodeAt(n)
      }
      return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
    }
    var extName = base64.split(',')[0].match(/data\:\S+\/(\S+);/)
    if (extName) {
      extName = extName[1]
    } else {
      reject(new Error('base64 error'))
    }
    fileName = fileName ? (/\.(jpe?g|png|gif|bmp)/i.test(fileName) ? fileName : fileName + '.' + extName) : getNewFileId() + '.' + extName
    if (typeof plus === 'object') {
      var basePath = '_doc'
      var dirPath = 'uniapp_file'
      var filePath = basePath + '/' + dirPath + '/' + fileName
      if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {
        plus.io.resolveLocalFileSystemURL(basePath, function(entry) {
          entry.getDirectory(dirPath, {
            create: true,
            exclusive: false,
          }, function(entry) {
            entry.getFile(fileName, {
              create: true,
              exclusive: false,
            }, function(entry) {
              entry.createWriter(function(writer) {
                writer.onwrite = function() {
                  resolve(filePath)
                }
                writer.onerror = reject
                writer.seek(0)
                writer.writeAsBinary(dataUrlToBase64(base64))
              }, reject)
            }, reject)
          }, reject)
        }, reject)
        return
      }
      var bitmap = new plus.nativeObj.Bitmap(fileName)
      bitmap.loadBase64Data(base64, function() {
        bitmap.save(filePath, {}, function() {
          bitmap.clear()
          resolve(filePath)
        }, function(error) {
          bitmap.clear()
          reject(error)
        })
      }, function(error) {
        bitmap.clear()
        reject(error)
      })
      return
    }
    if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
      var filePath = wx.env.USER_DATA_PATH + '/' + fileName
      wx.getFileSystemManager().writeFile({
        filePath: filePath,
        data: dataUrlToBase64(base64),
        encoding: 'base64',
        success: function() {
          resolve(filePath)
        },
        fail: function(error) {
          reject(error)
        }
      })
      return
    }
    reject(new Error('not support'))
  })
}
